<template>
  <div>
    <div>
      <c-table-box
        ref="cTableBox"
        hide-func
        checkbox
        :other-filters="otherFilters"
        :table-config="tableConfig"
        @selection-change="selectionChange"
      >
        <template #btn>
          <c-permission v-if="type==='all'" code="all">
            <c-button opt-code="change" type="primary" @click="handleChangeRebate">变更返利政策</c-button>
            <c-button opt-code="activation" type="primary" @click="handleActive">激活返利</c-button>
            <c-button opt-code="export" type="primary" @click="handleExport">导出</c-button>
          </c-permission>
          <c-permission v-else-if="type==='apply'" code="apply">
            <c-button opt-code="edit" type="primary" @click="handleEdit">编辑</c-button>
            <c-button opt-code="submit" type="primary" @click="handleSubmit">提报</c-button>
            <!-- <c-button opt-code="import" type="primary" @click="handleImport">导入</c-button> -->
            <c-button opt-code="export" type="primary" @click="handleExport">导出</c-button>
          </c-permission>
          <c-permission v-else-if="type==='execute'" code="execute">
            <c-button opt-code="execute" type="primary" @click="handleRebateExe">返利执行</c-button>
            <c-button opt-code="import" type="primary" @click="handleImport">导入</c-button>
            <c-button opt-code="export" type="primary" @click="handleExport">导出</c-button>
          </c-permission>
        </template>
      </c-table-box>
    </div>
    <import-files v-if="importVisible" title="导入" :visible.sync="importVisible" :config="fileImportConfig" @success="handleImportSuccess" />
    <export-files v-if="exportVisible" title="导出" :config="exportAllConfig" :visible.sync="exportVisible" @success="handleExportSuccess" />
    <!-- <change v-if="showChange" :id="activeRowId" :page-show.sync="showChange" @success="refreshTable" />
    <edit-form v-if="showEdit" :id="activeRowId" :page-show.sync="showEdit" @success="refreshTable" />
    <rebate-exe v-if="showRebateExe" :id="activeRowId" :page-show.sync="showRebateExe" @success="refreshTable" />
    <detail-page v-if="showDetail" :id="activeRowId" :page-show.sync="showDetail" /> -->
  </div>
</template>
<script>
// import Change from './change.vue'
// import EditForm from '../editForm/index.vue'
// import RebateExe from '../rebateExe.vue'
// import detailPage from '../detail.vue'
import { submitBatch, saveRebateState } from '@/api/shopRebate'
import { otherFiltersItem } from '@/utils/index'

export default {
  name: 'List',
  // components: { Change, EditForm, RebateExe, detailPage },

  props: {
    type: {
      type: String,
      default: ''
    },
    activeType: {
      type: String,
      default: ''
    },
    serachFilters: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      exportVisible: false,
      importVisible: false,
      tableSelected: [],
      // showRebateExe: false,
      // showDetail: false,
      activeTabIndex: 0,
      activeRowId: '',
      typeFilters: [],
      handlefilters: [],
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/shopRebate/page`,
        buttonGroupCode: 'default',
        hideSearchBar: true,
        tabIndex: 0,
        pageSize: 10,
        order: 'desc',
        sort: 'createTime',
        // 表格字段动态配置
        setting: [
          {
            prop: 'rebateApplyCode',
            label: '返利申请单号',
            minWidth: '220',
            className: 'btn-green',
            isButton: true,
            clickFun: this.handleDetail
          },
          {
            prop: 'constCode',
            label: '门店建设项目号',
            minWidth: '180'
          },
          {
            prop: 'schedule',
            label: '返利进度',
            minWidth: '130',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'SCHEDULE'
            }
          },
          {
            prop: 'dheadAcceptResult',
            label: '门头验收结果',
            minWidth: '150',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'ACCEPT_RESULT'
            }
          },
          {
            prop: 'dheadAcceptQualifiedTime',
            label: '门头验收合格时间',
            minWidth: '150'
          },
          {
            prop: 'shopAcceptResult',
            label: '卖场硬装验收结果',
            minWidth: '140',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'ACCEPT_RESULT'
            }
          },
          {
            prop: 'shopAcceptQualifiedTime',
            label: '卖场硬装验收合格时间',
            minWidth: '170'
          },
          {
            prop: 'customerDutySoftwearResult',
            label: '经销商责任软装结果',
            minWidth: '110',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'ACCEPT_RESULT'
            }
          },
          {
            prop: 'softAcceptQualifiedTime',
            label: '经销商责任软装验收合格时间',
            minWidth: '170'
          },
          {
            prop: 'marketType',
            label: '报图类型',
            minWidth: '110',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'MARKET_TYPE'
            }
          },
          {
            prop: 'officeName',
            label: '所属办事处',
            minWidth: '110'
          },
          {
            prop: 'shopCode',
            label: '所属门店编码',
            minWidth: '110'
          },
          {
            prop: 'shopName',
            label: '所属门店',
            minWidth: '110'
          },
          {
            prop: 'clientName',
            label: '所属客户',
            minWidth: '130'
          },
          {
            prop: 'constType',
            label: '门店建设类型',
            minWidth: '130',
            render(h, row) {
              return h('c-dict-range-view', {
                props: {
                  dictTypeCode: 'CONST_TYPE',
                  value: row.constType
                }
              })
            }
          },
          {
            prop: 'acceptDheadTotalArea',
            label: '门头验收总面积',
            minWidth: '140'
          },
          {
            prop: 'acceptWholeTotalArea',
            label: '验收整装总面积',
            minWidth: '140'
          },
          {
            prop: 'acceptSimpleTotalArea',
            label: '验收简装总面积',
            minWidth: '140'
          },
          {
            prop: 'unAccDheadArea',
            label: '非本次验收门头总面积',
            minWidth: '160'
          }, {
            prop: 'unAccShopArea',
            label: '非本次验收卖场总面积',
            minWidth: '160'
          },
          {
            prop: 'isMonthReturn',
            label: '是否涉及月返',
            minWidth: '130',
            formatData: ({ isMonthReturn }) => {
              if (isMonthReturn === 0 || isMonthReturn === 1) return isMonthReturn === 0 ? '否' : '是'
              else ''
            }
          },
          {
            prop: 'isPaymentException',
            label: '装修款是否存在异常',
            minWidth: '130',
            formatData: ({ isPaymentException }) => {
              if (isPaymentException === 0 || isPaymentException === 1) return isPaymentException === 0 ? '否' : '是'
              else ''
            }
          },
          {
            prop: 'isShopHardcoverHandle',
            label: '硬装是否处理',
            minWidth: '110',
            formatData: ({ isShopHardcoverHandle }) => {
              if (isShopHardcoverHandle === 0 || isShopHardcoverHandle === 1) return isShopHardcoverHandle === 0 ? '否' : '是'
              else ''
            }
          },
          {
            prop: 'isShopSoftwearHandle',
            label: '软装是否处理',
            minWidth: '130',
            formatData: ({ isShopSoftwearHandle }) => {
              if (isShopSoftwearHandle === 0 || isShopSoftwearHandle === 1) return isShopSoftwearHandle === 0 ? '否' : '是'
              else ''
            }
          },
          {
            prop: 'isOpen',
            label: '是否开业',
            minWidth: '130',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'OPEN_STATE'
            }
          },
          {
            prop: 'openSchedule',
            label: '开业进度',
            minWidth: '130',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'OPEN_SCHEDULE'
            }
          },
          {
            prop: 'declareType',
            label: '申报类型',
            minWidth: '130',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'DECLARE_TYPE'
            }
          },
          {
            prop: 'isRebate',
            label: '返利是否结束',
            minWidth: '130',
            formatData: ({ isRebate }) => {
              if (isRebate === 0 || isRebate === 1) return isRebate === 0 ? '否' : '是'
              else return ''
            }
          }, {
            prop: 'actualEndTime',
            label: '实际返利完成时间',
            minWidth: '130'
          }, {
            prop: 'actualOpenTime',
            label: '实际开业时间',
            minWidth: '130'
          }

        ]
      }
    }
  },
  computed: {
    otherFilters() {
      return [...this.serachFilters, ...this.typeFilters]
    },
    selectedIds() {
      return this.tableSelected.map(row => {
        return row.id
      })
    },
    exportAllConfig() {
      return [{
        code: 'export',
        name: '返利管理',
        dataApi: '/slm-admin/api/v1/shopRebate/export?type=0',
        selectedRows: this.tableSelected,
        paramsRaw: {},
        headers: { 'Permission-perCode': 'storerebate' },
        filtersRaw: this.otherFilters,
        queryField: 'id'
      }]
    },
    fileImportConfig() {
      return [{
        code: 'importUpdate',
        name: '返利执行',
        async: false,
        apiUrl: '/slm-admin/api/v1/shopRebate/importExcel?type=0'
      }]
    }
  },
  watch: {
    type: {
      handler(v) {
        this.setOtherFilters(v)
      },
      immediate: true
    },
    serachFilters: {
      handler(v) {
        if (this.activeType !== this.type) return
        this.$nextTick(() => {
          this.$refs.cTableBox.initTableData()
        })
      }
    }
  },
  activated() {
    if (this.ready && this.refreshTable) {
      this.refreshTable()
    }
  },
  deactivated() {
    this.ready = true
  },
  created() {
  },
  methods: {
    // 清空搜索数据
    clearSearch() {

    },
    // 切换tab，改变过滤数据条件
    setOtherFilters(v) {
      switch (v) {
        case 'all':
          this.typeFilters = []
          break
        case 'apply':
          this.typeFilters = [
            otherFiltersItem('isEnd', '0', '='),
            otherFiltersItem('schedule', 'A', '=')]// 已保存
          break
        case 'execute':
          this.typeFilters = [
            otherFiltersItem('isEnd', '0', '='),
            otherFiltersItem('schedule', 'C', '=')
          ]// 待执行
          break
      }
    },
    // 导入
    handleImport() {
      this.importVisible = true
    },
    // 导入成功
    handleImportSuccess() {
      this.refreshTable()
    },
    // 刷新表格
    refreshTable(v = 'onPage') {
      this.$nextTick(() => {
        this.$refs.cTableBox.initTableData(v)
      })
    },
    // 导出成功
    handleExportSuccess() {
      this.$message.success('导出成功！')
    },
    // 获取搜索条件
    handleSearch(data) {
      this.handlefilters = [...data.filtersRaw]
    },
    // 编辑
    handleEdit() {
      if (!this.singleJudge(this.tableSelected, '编辑', true)) {
        return
      }
      this.$router.push({ name: 'RebateEdit', query: { id: this.tableSelected[0].id }})
    },
    // 返利执行
    handleRebateExe() {
      if (!this.singleJudge(this.tableSelected, '返利执行', true)) {
        return
      }
      this.$router.push({ name: 'RebateExecute', query: { id: this.tableSelected[0].id }})
    },

    // 返利变更
    handleChangeRebate() {
      if (!this.singleJudge(this.tableSelected, '变更', true)) {
        return
      }
      if (this.tableSelected[0].schedule !== 'C') {
        this.$message.warning('返利进度为【待执行】状态才能变更')
        return
      }
      this.$router.push({ name: 'RebateChange', query: { id: this.tableSelected[0].id }})
    },
    // 激活返利
    handleActive() {
      if (!this.singleJudge(this.tableSelected, '激活', true)) {
        return
      }
      if (this.tableSelected[0].declareType === 'A' || this.tableSelected[0].schedule !== 'D') {
        this.$message.warning('当前状态不可激活')
        return
      }
      this.$confirm(`是否确认激活返利?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 激活
        const formData = { ...this.tableSelected[0], schedule: 'A', declareType: 'A' }
        saveRebateState(formData).then(res => {
          if (res.success) {
            this.$message.success('激活成功')
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },
    // 返利详情
    handleDetail(data) {
      this.$router.push({ name: 'RebateDetail', query: { id: data.id }})
    },
    // 提报
    handleSubmit() {
      if (!this.singleJudge(this.tableSelected, '提报', false)) {
        return
      }
      this.$confirm(`是否确认将勾选的${this.tableSelected.length}条返利数据提交审核?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 提报
        submitBatch(this.selectedIds).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '提报成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },

    // 导出
    handleExport() {
      // const querys = this.$refs.refTable.getAllFilters()
      // const searchFilters = (querys && querys.searchBarFilter) || []
      // this.exportData.filtersRaw = [...this.otherFilters, ...searchFilters]
      // this.visible = true
      this.exportVisible = true
    },
    selectionChange(rows) {
      this.tableSelected = rows
    }
  }
}
</script>
